import {useEffect,useCallback,useMemo,useRef} from 'react'
import useRequest from './useRequest'
import useUpdateEffect  from './useUpdateEffect'
/**
 *  @description 统一处理表格类请求
 *  @param {function} service promise异步任务
 *  @param {Object} option 参数
 * 
 **/
function usePaginated(service,options){
  const { paginated, defaultPageSize = 10, refreshDeps = [], fetchKey, ...restOptions } = options;

  useEffect(() => {
    if (fetchKey) {
      console.error("useRequest pagination's fetchKey will not work!");
    }
  }, []);

  const { data, params, run, loading, ...rest } = useRequest(service, {
    defaultParams: [
      {
        current: 1,
        pageSize: defaultPageSize,
      },
    ],
    ...restOptions,
  });

  const {
    current = 1,
    pageSize = defaultPageSize,
    sorter = {},
    filters = {},
  } = params && params[0] ? params[0] : {};

  // 只改变 pagination，其他参数原样传递
  const runChangePagination = useCallback(
    (paginationParams) => {
      const [oldPaginationParams, ...restParams] = params;
      run(
        {
          ...oldPaginationParams,
          ...paginationParams,
        },
        ...restParams,
      );
    },
    [run, params],
  );

  const total = data?.data?.total || 0;
  const totalPage = useMemo(() => Math.ceil(total / pageSize), [pageSize, total]);

  const onChange = useCallback(
    (c, p) => {
      let toCurrent = c <= 0 ? 1 : c;
      const toPageSize = p <= 0 ? 1 : p;

      const tempTotalPage = Math.ceil(total / toPageSize);
      if (toCurrent > tempTotalPage) {
        toCurrent = tempTotalPage;
      }
      runChangePagination({
        current: c,
        pageSize: p,
      });
    },
    [total, runChangePagination],
  );

  const changeCurrent = useCallback(
    (c) => {
      onChange(c, pageSize);
    },
    [onChange, pageSize],
  );

  const changePageSize = useCallback(
    (p) => {
      onChange(current, p);
    },
    [onChange, current],
  );

  const changeCurrentRef = useRef(changeCurrent);
  changeCurrentRef.current = changeCurrent;
  /* 分页场景下，如果 refreshDeps 变化，重置分页 */
  useUpdateEffect(() => {
    /* 只有自动执行的场景， refreshDeps 才有效 */
    if (!options.manual) {
      changeCurrentRef.current(1);
    }
  }, [...refreshDeps]);

  // 表格翻页 排序 筛选等
  const changeTable = useCallback(
    (p, f, s) => {
      runChangePagination({
        current: p.current,
        pageSize: p.pageSize || defaultPageSize,
        filters: f,
        sorter: s,
      });
    },
    [filters, sorter, runChangePagination],
  );

  return {
    loading,
    data,
    params,
    run,
    pagination: {
      current,
      pageSize,
      total,
      totalPage,
      onChange,
      changeCurrent,
      changePageSize,
    },
    tableProps: {
      dataSource: data?.data.records || [],
      loading,
      onChange: changeTable,
      pagination: {
        current,
        pageSize,
        total,
      },
    },
    sorter,
    filters,
    ...rest,
  }
}

export default usePaginated